import { getUserInfo, login, getUserInfoById } from '@/api/user'
import { getToken, setToken, removeToken, setTimestamp } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, info) {
      state.userInfo = info
    },
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 退出登录：
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
    },
    async  setUserInfo(context) {
      try {
        // 获取用户的基本信息
        const res = await getUserInfo()
        console.log(res, 'setUserInfo')
        const info = await getUserInfoById(res.data.userId)
        console.log(info, 'getUserInfoById')
        context.commit('setUserInfo', { ...res.data, ...info.data })
      } catch (error) {
        console.log(error, '获取用户信息失败')
      }
    },
    async userLogin(context, formData) {
      console.log(context, 'context')
      const res = await login(formData)
      console.log(res, 'res')
      context.commit('setToken', res.data)
      // 存取获取token时的时间戳
      setTimestamp()
    }
  }
}

